//index.js
//获取应用实例
const moment = require('../../utils/moment.js');
var wxCharts = require('../../utils/wxcharts.js');
var lineChart = null;
var startPos = null;
const app = getApp()
Page({
  data: {
    date: "null",
    dateImg: "../../images/sign-date.png",
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    /*HealthReport:[{
      url:'../health_report/health_report'
    }],*/
    WeightRecord:[{
      url:'../scrollline/scrollline'
      }],

    currentWeight: '0KG',
    bmi: '0',
    bfr: '0.00%',

    listHotCourse:[]
 },

fetchDataFromServer () {
  let that = this
  app.apis().getArticles(function (res) {
    console.log(res)
    let articles = res.data._embedded.article
    let data = []
    articles.forEach(function (article) {
      data.push({
        url: '../detail_news/detail_news?id=' + article.id,
        course_pic_small: article.image,
        course_name: article.title
      })
    })
    console.log(data)
    that.setData({ 'listHotCourse': data })
  })
},
  initHealthyReport: function (options) {
    let healthy_report_source = wx.getStorageSync('healthy_report_source')
    if (healthy_report_source) {
      let bmi = healthy_report_source.weight / (healthy_report_source.height * healthy_report_source.height)
      this.setData({
        currentWeight: healthy_report_source.weight + 'KG',
        bmi: bmi.toFixed(2),
        bfr: (1.2 * bmi + 0.23 * healthy_report_source.age - 5.4 - 10.8 * healthy_report_source.sex).toFixed(2) + '%',
      })
    }
  },


  /*曲线*/
  touchHandler: function (e) {
    lineChart.scrollStart(e);
  },
  moveHandler: function (e) {
    lineChart.scroll(e);
  },
  touchEndHandler: function (e) {
    lineChart.scrollEnd(e);
    lineChart.showToolTip(e, {
      format: function (item, category) {
        return category + ' ' + item.name + ':' + item.data
      }
    });
  },
  createSimulationData: function (weightLogs) {
    var categories = [];
    var data = [];
    weightLogs.forEach(item => {
      categories.push(item.date);
      data.push(parseFloat(item.weight));
    })
    return {
      categories: categories,
      data: data
    }
  },

  //获取选定的时间
  bindDateChange: function (e) {
    console.log(e.detail.value)
    this.setData({
      date: e.detail.value
    })
    this.getMealList();
  },

  listSign: function () {
    this.getMealList();
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onShow() {
    app.userInfoReadyCallback2 = this.reflashData
    this.initHealthyReport()
    this.setDateToToday()
  },

  setDateToToday () {
    // 把日期选择器的时间设置为当天
    this.setData({
      date: moment().format('YYYY-MM-DD')
    })
  },

  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }

    this.fetchDataFromServer()
  },

/*曲线*/
  initwindowWidth: function (simulationData) {
    var windowWidth = 100;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }
    
    lineChart = new wxCharts({
      canvasId: 'lineCanvas',
      type: 'line',
      categories: simulationData.categories,
      animation: false,
      series: [{
        name: '体重',
        data: simulationData.data,
        format: function (val, name) {
          return val.toFixed(2) + 'KG';
        }
      }],
      xAxis: {
        disableGrid: false
      },
      yAxis: {
        title: '体重 (KG)',
        format: function (val) {
          return val.toFixed(2);
        },
        min: 35,
        max: 60
      },
      width: windowWidth,
      height: 110,
      dataLabel: true,
      dataPointShape: true,
      enableScroll: true,
      extra: {
        lineStyle: 'curve'
      }
    });
  },


  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  reflashData() {
    app.apis().getWeightLogs(app.globalData.userObject.id).then(data => {
      this.initwindowWidth(this.createSimulationData(data._embedded.weight_logs))
    })
  }
})
